import { defineStore } from "pinia";
import { ref } from "vue";
import { get, post } from "../../utils/request";
import { computed } from "vue";

export const useUserStore = defineStore("user", () => {
  // 状态定义
  const userData = ref({
    id: 1,
    phone: "17870113181",
    password: "123123",
    role: "older",
    name: "byebye",
    age: 2048,
    sex: "male",
    bloodType: null,
    createdAt: "2025-05-20T09:29:54.000Z",
    updatedAt: "2025-05-20T13:19:50.000Z",
  });

  const curUserId = computed(() => userData.value.id);

  const token = ref(null);

  // 设置方法
  function setUserData(data) {
    userData.value = data;
    uni.setStorageSync("userData", JSON.stringify(data));
  }

  const updateUserData = async (updateData) => {
    try {
      console.log("updateUserData", updateData);

      // 发送API请求 - 添加错误状态码处理
      const response = await post("/users/update", updateData, "api/v1", {
        method: "POST",
      });
      console.log("updateUserData response", response);
    } catch (error) {
      console.error("更新用户数据失败:", error);
      uni.showToast({
        title: "网络异常",
        icon: "none",
        duration: 2000,
      });
      throw error;
    }
  };

  function setToken(tokenValue) {
    token.value = tokenValue;
    // 保存到本地存储中
    uni.setStorageSync("token", tokenValue);
  }
  async function refreshToken() {
    try {
      const response = await post(
        "/auth/refresh",
        { token: token.value },
        "api/v1"
      );
      setToken(response.newToken);
    } catch (error) {
      console.error("刷新 Token 失败:", error);
      throw new Error("无法刷新 Token，请重新登录");
    }
  }
  function loadFromStorage() {
    //从本地存储中加载数据
    token.value = uni.getStorageSync("token") || null;
    userData.value = uni.getStorageSync("userData")
      ? JSON.parse(uni.getStorageSync("userData"))
      : null;
  }

  // Add methods for editing user info
  const getUserData = computed(() => userData.value);

  // 登录方法
  function login(data, tokenValue) {
    // 先设置token再设置用户数据
    console.log("login", data, tokenValue);
    setToken(tokenValue);
    try {
      if (typeof data === "object") {
        setUserData(data);
      } else if (typeof data === "string") {
        setUserData(JSON.parse(data));
      }
    } catch (error) {
      console.error("无法解析用户数据:", error);
      throw error;
    }
  }

  // 设置方法
  function setUserData(data) {
    userData.value = data;
    uni.setStorageSync("userData", JSON.stringify(data));
  }

  function setToken(tokenValue) {
    token.value = tokenValue;
    // 同时保存到本地存储和内存
    uni.setStorageSync("token", tokenValue);
  }

  // 登出方法
  function logout() {
    setUserData(null);
    setToken(null);
    uni.removeStorageSync("token");
    uni.removeStorageSync("userData");
    uni.reLaunch({
      url: "/pages/login/login",
    });
  }

  // 派生状态（getters）
  const isLoggedIn = computed(() => !!token.value);
  const getToken = computed(() => token.value);
  const getRole = computed(() => userData.value.role);

  return {
    getRole,

    loadFromStorage,
    token,
    getToken,
    setToken,
    curUserId,

    userData,
    getUserData,
    setUserData,
    updateUserData,

    login,
    logout,
    isLoggedIn,
  };
});
